<template>
  <main>
    <video id="video" autoplay ref="videoRef"></video>
  </main>
</template>
<script setup lang="ts">
import { onMounted, ref, watch } from 'vue'
const videoRef = ref<HTMLVideoElement>()
const props = defineProps({
  currDeviceId: String
})

const getMediaStream = (deviceId: string) => {
  if (!deviceId) {
    return
  }
  const videoElement = videoRef.value!
  const constrains = {
    audio: false,
    video: { deviceId, width: 1280, height: 720 }
  } as MediaStreamConstraints
  navigator.mediaDevices.getUserMedia(constrains).then((stream) => {
    videoElement.srcObject = stream
  })
}

onMounted(() => {
  if (props.currDeviceId) {
    getMediaStream(props.currDeviceId)
  }
})

watch(
  () => props.currDeviceId,
  () => {
    if (props?.currDeviceId) {
      getMediaStream(props.currDeviceId)
    }
  }
)
</script>
